package com.yaodian100.mall.member.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.cobranding.entity.DPNStore;
import com.yaodian100.ec.cobranding.service.DPNService;
import com.yaodian100.ec.delivery.entity.ViewDeliveryRule;
import com.yaodian100.ec.delivery.service.DeliveryRuleService;
import com.yaodian100.ec.member.entity.AddressBook;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.AddessService;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.entity.Orders.ORDER_LOGISTIC_PROVIDER_TP;
import com.yaodian100.ec.order.service.OrderModifyService;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.mall.member.util.UserData;

public class OrderModAction extends ActionSupport implements Preparable {
	private static final long serialVersionUID = 4348284462838267080L;
	private final Logger logger = LoggerFactory.getLogger(OrderModAction.class);
	private OrderModifyService orderModifyService;
	private String orderId;
	@Resource
	private MemberService memberService;
	private Member member;
	private String paytype;// 付款方式
	private BigDecimal codFee = new BigDecimal(0);// COD﹣收取手續費
	@Resource
	private AddessService addressService;
	private ArrayList<String> orderChangeInfo = new ArrayList();
	@Resource
	private DomainService<Menu> menuService;
	private Menu paymentTpMenu; // 與 getter, setter
	@Autowired
	private DPNService dpnService;
	@Autowired
	private DeliveryRuleService deliveryRuleService;
	@Autowired
	private OrderService orderService;

	private String contactName;
	private String areaCode;
	private String phone;
	private String extension;
	private String mobile;
	private String province;
	private String city;
	private String district;
	private String addr;
	private String zipCode;
	private String storeId;
	private UserData userData;
	private List<AddressBook> abList;
	private Map<String, String> provincesMap;
	private String showCod = "false";
	private String version;
	private String showPos = "N";
	// 惡意訂購不允許使用COD付款
	private String showCodAlert = "N";
	private Menu billBankSingleCodeMenu; // 快钱menu code單期支付
	// 发票信息
	private String invotype;// 01－个人，02－单位
	private String invoTitle;

	private String allowSplit;

	public String modPay() throws Exception {
		member = memberService.get(UserLoginData.getMemberId());
		Orders orders = orderService.get(orderId);
		if (ORDER_LOGISTIC_PROVIDER_TP.NOT_COD_PROVIDER.getValue().equals(orders.getLogisticProviderTp())) {
			showCod = "false";
			showPos = "N";
		} else {
			ViewDeliveryRule viewDeliveryRule = deliveryRuleService.canUseCodByOrderId(orderId);
			if ("Y".equals(viewDeliveryRule.getIsCod()) || "Y".equals(viewDeliveryRule.getIsPos())) {
				showCod = "true";
			}
			if ("Y".equals(viewDeliveryRule.getIsPos())) {
				showPos = "Y";
			}
			// 订单任一商品为scm不允许cod / pos
			if ("2".equals(orders.getOrderType())) {
				showCod = "false";
				showPos = "N";
			}
		}
		String actionResult = memberService.badOrderCheck(member.getMemberId(), orders.getReceiverAddr(), orders
				.getReceiverMobile(), orders.getReceiverPhone());
		if (!"true".equals(actionResult)) {
			showCodAlert = "Y";
			showCod = "false";
			showPos = "N";
		}
		return "modPay";
	}

	public String modAddres() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		Orders order = orderModifyService.get(orderId);
		// 地址簿-省
		provincesMap = deliveryRuleService.getOrderProvinces(orderId);
		if ("30".equals(order.getReceiverTp())) {
			if (StringUtils.isNotBlank(order.getStoreId())) {
				CommonCriteria crit = new CommonCriteria();
				crit.addEq("storeId", order.getStoreId());
				List<DPNStore> DPNStores = dpnService.getDPNStoretList(crit);
				if (DPNStores.size() > 0) {
					request.setAttribute("storeAreaInit", DPNStores.get(0).getStoreArea());
				}
			}
			return "modAddresDaphne";
		} else {
			return "modAddres";
		}
	}

	public String modPayTp() throws Exception {
		try {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			orderChangeInfo = orderModifyService.updateOrderPaymentTp(orderId, paytype, false, memberId, allowSplit);
		} catch (Exception e) {
			addActionMessage(e.getLocalizedMessage());
			return "orderDetailPage";
		}
		return "orderDetailPage";
	}

	public String modAddresExe() throws Exception {
		try {
			boolean canSave = true;
			Orders order = orderModifyService.get(orderId);
			Map<String, Object> attrs = new HashMap<String, Object>();
			attrs.put("contactName", contactName);
			attrs.put("areaCode", areaCode.trim());
			attrs.put("phone", phone.trim());
			attrs.put("extension", extension.trim());
			attrs.put("mobile", mobile);
			if (province == null) {
				province = order.getReceiverProvince();
			}
			if (city == null) {
				city = order.getReceiverCity();
			}
			if (addr == null) {
				addr = order.getReceiverAddr();
			}
			attrs.put("province", province);
			attrs.put("city", city);
			attrs.put("addr", addr);
			if ("30".equals(order.getReceiverTp())) {// 達芙妮
				if (district == null) {
					district = order.getReceiverArea();
				}
				if (storeId == null) {
					storeId = order.getStoreId();
				}
				attrs.put("district", district);
				attrs.put("storeId", storeId);
			} else {
				if (zipCode == null) {
					zipCode = order.getReceiverZip();
				}
				if (zipCode.length() > 6 || !(Integer.parseInt(zipCode) > 0)) {
					canSave = false;
				}

				if (district == null) {
					district = order.getReceiverArea();
				}
				attrs.put("zipCode", zipCode);
				district = district.split(",")[0];
				if (district.substring(0, 1).equals("※")) {
					district = district.substring(1);
				}
				attrs.put("district", district);
				attrs.put("version", version);
			}
			if (canSave) {
				orderChangeInfo = orderModifyService.updateOrderAddres(orderId, attrs);
			} else {
				throw new Exception("zipCode error");
			}
		} catch (Exception e) {
			addActionMessage(e.getLocalizedMessage());
			return "orderDetailPage";
		}
		return "orderDetailPage";
	}

	// 从收货地址簿选取
	public String loadMyAddBook() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		userData = new UserData(request, response);
		Orders order = orderService.get(orderId);
		String paymentTp = Arrays.asList("30", "60").contains(order.getPaymentTp()) ? order.getPaymentTp() : "";
		Map<String, String> drMap = deliveryRuleService.findDeliveryType("order", orderId);
		String deliveryType = drMap.get("deliveryType");
		if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
			abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, drMap.get("fromProvince"),
					drMap.get("fromCity"), drMap.get("fromDistrict"), paymentTp);
		} else {
			// 大材积
			Map<String, String> prodVolumeMap = orderService.chkVolumeOfOrderDetail(orderId);
			if (prodVolumeMap.size() > 0) {
				abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "", true);
			} else {
				abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "", paymentTp);
			}
		}
		return "myAddBook";
	}

	// 修改发票
	public String modInvoice() throws Exception {
		member = memberService.get(UserLoginData.getMemberId());
		Orders orders = orderService.get(orderId);
		return "modInvoice";
	}

	// 修改发票
	public String modInvoiceExt() throws Exception {
		member = memberService.get(UserLoginData.getMemberId());
		Orders orders = orderService.get(orderId);
		orders.setInvoiceTp(invotype);
		if ("02".equals(invotype)) {
			orders.setInvoiceTitle(invoTitle);
		} else {
			orders.setInvoiceTitle("");
		}
		orderModifyService.update(orders);
		return "orderDetailPage";
	}

	// 修改商品缺货配送处理方法
	public String modAllowSplit() throws Exception {
		member = memberService.get(UserLoginData.getMemberId());
		return "modAllowSplit";
	}

	// 修改商品缺货配送处理方法
	public String modAllowSplitExt() throws Exception {
		member = memberService.get(UserLoginData.getMemberId());
		Orders orders = orderService.get(orderId);
		if ("Y".equals(allowSplit)) {
			orders.setAllowSplit("Y");
		} else {
			orders.setAllowSplit("N");
		}
		orderModifyService.update(orders);
		return "orderDetailPage";
	}

	public String getOrderId() {
		return orderId;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	@Override
	public void prepare() throws Exception {
		codFee = addressService.getCodFee();// COD﹣收取手續費
		if (paymentTpMenu == null) {
			paymentTpMenu = menuService.get("Order.PaymentTp");
		}
		if (billBankSingleCodeMenu == null) {
			billBankSingleCodeMenu = menuService.get("99BillSingle.BankCode");
		}

	}

	public void setOrderModifyService(OrderModifyService orderModifyService) {
		this.orderModifyService = orderModifyService;
	}

	public String getPaytype() {
		return paytype;
	}

	public void setPaytype(String paytype) {
		this.paytype = paytype;
	}

	public ArrayList<String> getOrderChangeInfo() {
		return orderChangeInfo;
	}

	public void setOrderChangeInfo(ArrayList<String> orderChangeInfo) {
		this.orderChangeInfo = orderChangeInfo;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public BigDecimal getCodFee() {
		return codFee;
	}

	public void setCodFee(BigDecimal codFee) {
		this.codFee = codFee;
	}

	public void setAddressService(AddessService addressService) {
		this.addressService = addressService;
	}

	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public void setPaymentTpMenu(Menu paymentTpMenu) {
		this.paymentTpMenu = paymentTpMenu;
	}

	public Menu getPaymentTpMenu() {
		return paymentTpMenu;
	}

	public String getContactName() {
		return contactName;
	}

	public void setContactName(String contactName) {
		this.contactName = contactName;
	}

	public String getAreaCode() {
		return areaCode;
	}

	public void setAreaCode(String areaCode) {
		this.areaCode = areaCode;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getExtension() {
		return extension;
	}

	public void setExtension(String extension) {
		this.extension = extension;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getDistrict() {
		return district;
	}

	public void setDistrict(String district) {
		this.district = district;
	}

	public String getAddr() {
		return addr;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}

	public String getStoreId() {
		return storeId;
	}

	public void setStoreId(String storeId) {
		this.storeId = storeId;
	}

	public String getZipCode() {
		return zipCode;
	}

	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}

	public List<AddressBook> getAbList() {
		return abList;
	}

	public void setAbList(List<AddressBook> abList) {
		this.abList = abList;
	}

	public Map<String, String> getProvincesMap() {
		return provincesMap;
	}

	public void setProvincesMap(Map<String, String> provincesMap) {
		this.provincesMap = provincesMap;
	}

	public String getShowCod() {
		return showCod;
	}

	public void setShowCod(String showCod) {
		this.showCod = showCod;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public String getShowPos() {
		return showPos;
	}

	public void setShowPos(String showPos) {
		this.showPos = showPos;
	}

	public String getShowCodAlert() {
		return showCodAlert;
	}

	public void setShowCodAlert(String showCodAlert) {
		this.showCodAlert = showCodAlert;
	}

	public Menu getBillBankSingleCodeMenu() {
		return billBankSingleCodeMenu;
	}

	public void setBillBankSingleCodeMenu(Menu billBankSingleCodeMenu) {
		this.billBankSingleCodeMenu = billBankSingleCodeMenu;
	}

	public String getInvotype() {
		return invotype;
	}

	public void setInvotype(String invotype) {
		this.invotype = invotype;
	}

	public String getInvoTitle() {
		return invoTitle;
	}

	public void setInvoTitle(String invoTitle) {
		this.invoTitle = invoTitle;
	}

	public String getAllowSplit() {
		return allowSplit;
	}

	public void setAllowSplit(String allowSplit) {
		this.allowSplit = allowSplit;
	}

}
